import sys
from PySide2.QtWidgets import (QApplication, QMainWindow, QWidget, QVBoxLayout, QHBoxLayout, 
                             QLabel, QLineEdit, QPushButton, QDialog, QDateEdit, 
                             QTimeEdit, QSpinBox, QComboBox, QScrollArea, QFrame,
                             QTextEdit, QCheckBox, QProgressBar, QMessageBox)
from PySide2.QtCore import QDate, QTime, Qt, Signal
from PySide2.QtGui import QIcon

class ScheduleItem(QFrame):
    deleteClicked = Signal(int)
    toggleClicked = Signal(int)
    
    def __init__(self, schedule_id, name, date, time, limit, repeat, enabled=True, parent=None):
        super().__init__(parent)
        self.schedule_id = schedule_id
        self.enabled = enabled
        
        # 创建UI元素
        self.name_label = QLabel(name)
        self.name_label.setStyleSheet("font-weight: bold;")
        
        self.date_label = QLabel(f"日期: {date}")
        self.time_label = QLabel(f"时间: {time}")
        self.limit_label = QLabel(f"每日上限: {limit}人")
        self.repeat_label = QLabel(f"重复: {self.get_repeat_text(repeat)}")
        self.status_label = QLabel("已启用" if enabled else "已禁用")
        self.status_label.setStyleSheet(f"""
            padding: 2px 5px;
            border-radius: 3px;
            background-color: {'#d1fae5' if enabled else '#f3f4f6'};
            color: {'#065f46' if enabled else '#4b5563'};
        """)
        
        # 操作按钮
        self.delete_btn = QPushButton()
        self.delete_btn.setIcon(QIcon.fromTheme("edit-delete"))
        self.delete_btn.setFlat(True)
        self.delete_btn.clicked.connect(lambda: self.deleteClicked.emit(self.schedule_id))
        
        self.toggle_btn = QPushButton()
        self.toggle_btn.setIcon(QIcon.fromTheme("media-playback-start" if enabled else "media-playback-stop"))
        self.toggle_btn.setFlat(True)
        self.toggle_btn.clicked.connect(lambda: self.toggleClicked.emit(self.schedule_id))
        
        # 布局
        top_layout = QHBoxLayout()
        top_layout.addWidget(self.name_label)
        top_layout.addStretch()
        top_layout.addWidget(self.delete_btn)
        top_layout.addWidget(self.toggle_btn)
        
        middle_layout = QHBoxLayout()
        middle_layout.addWidget(self.date_label)
        middle_layout.addWidget(self.time_label)
        middle_layout.addWidget(self.limit_label)
        
        bottom_layout = QHBoxLayout()
        bottom_layout.addWidget(self.repeat_label)
        bottom_layout.addWidget(self.status_label)
        bottom_layout.addStretch()
        
        main_layout = QVBoxLayout()
        main_layout.addLayout(top_layout)
        main_layout.addLayout(middle_layout)
        main_layout.addLayout(bottom_layout)
        
        self.setLayout(main_layout)
        self.setFrameShape(QFrame.StyledPanel)
        self.setStyleSheet("""
            ScheduleItem {
                border-left: 3px solid #4CAF50;
                background-color: #f8f9fa;
                padding: 8px;
                border-radius: 0 4px 4px 0;
            }
        """)
    
    def get_repeat_text(self, repeat):
        repeat_texts = {
            "daily": "每天",
            "weekdays": "工作日",
            "weekends": "周末",
            "once": "仅一次"
        }
        return repeat_texts.get(repeat, repeat)

class ScheduleDialog(QDialog):
    def __init__(self, parent=None):
        super().__init__(parent)
        self.setWindowTitle("定时任务管理")
        self.setWindowIcon(QIcon.fromTheme("clock"))
        self.setMinimumSize(500, 600)
        
        self.schedules = []
        
        self.init_ui()
        self.setup_styles()
    
    def init_ui(self):
        # 表单区域
        form_group = QWidget()
        form_layout = QVBoxLayout()
        
        # 任务名称
        name_layout = QHBoxLayout()
        name_layout.addWidget(QLabel("任务名称:"))
        self.name_edit = QLineEdit()
        self.name_edit.setPlaceholderText("例如: 上午添加校友")
        name_layout.addWidget(self.name_edit)
        
        # 日期和时间
        datetime_layout = QHBoxLayout()
        
        date_layout = QVBoxLayout()
        date_layout.addWidget(QLabel("开始日期:"))
        self.date_edit = QDateEdit()
        self.date_edit.setDate(QDate.currentDate().addDays(1))
        self.date_edit.setCalendarPopup(True)
        date_layout.addWidget(self.date_edit)
        
        time_layout = QVBoxLayout()
        time_layout.addWidget(QLabel("执行时间:"))
        self.time_edit = QTimeEdit()
        self.time_edit.setTime(QTime.currentTime().addSecs(3600))  # 默认下一小时
        time_layout.addWidget(self.time_edit)
        
        datetime_layout.addLayout(date_layout)
        datetime_layout.addLayout(time_layout)
        
        # 每日上限和重复模式
        limit_layout = QHBoxLayout()
        
        limit_sub_layout = QVBoxLayout()
        limit_sub_layout.addWidget(QLabel("每日添加上限:"))
        self.limit_spin = QSpinBox()
        self.limit_spin.setRange(1, 50)
        self.limit_spin.setValue(20)
        limit_sub_layout.addWidget(self.limit_spin)
        
        repeat_sub_layout = QVBoxLayout()
        repeat_sub_layout.addWidget(QLabel("重复模式:"))
        self.repeat_combo = QComboBox()
        self.repeat_combo.addItems(["每天", "工作日(周一至周五)", "周末(周六至周日)", "仅一次"])
        self.repeat_combo.setCurrentIndex(0)
        repeat_sub_layout.addWidget(self.repeat_combo)
        
        limit_layout.addLayout(limit_sub_layout)
        limit_layout.addLayout(repeat_sub_layout)
        
        # 添加按钮
        self.add_btn = QPushButton("添加任务")
        self.add_btn.setIcon(QIcon.fromTheme("list-add"))
        self.add_btn.clicked.connect(self.add_schedule)
        
        # 组装表单
        form_layout.addLayout(name_layout)
        form_layout.addLayout(datetime_layout)
        form_layout.addLayout(limit_layout)
        form_layout.addWidget(self.add_btn)
        form_group.setLayout(form_layout)
        
        # 任务列表区域
        self.schedule_list = QWidget()
        self.schedule_layout = QVBoxLayout()
        self.schedule_layout.setAlignment(Qt.AlignTop)
        self.schedule_list.setLayout(self.schedule_layout)
        
        # 滚动区域
        scroll_area = QScrollArea()
        scroll_area.setWidgetResizable(True)
        scroll_area.setWidget(self.schedule_list)
        
        # 主布局
        main_layout = QVBoxLayout()
        main_layout.addWidget(form_group)
        main_layout.addWidget(QLabel("已设置的定时任务:"))
        main_layout.addWidget(scroll_area)
        
        self.setLayout(main_layout)
    
    def setup_styles(self):
        self.setStyleSheet("""
            ScheduleDialog {
                background-color: #f9fafb;
            }
            
            QLabel {
                color: #374151;
            }
            
            QLineEdit, QDateEdit, QTimeEdit, QSpinBox, QComboBox {
                padding: 5px;
                border: 1px solid #d1d5db;
                border-radius: 4px;
                background-color: white;
            }
            
            QPushButton {
                padding: 6px 12px;
                border-radius: 4px;
                background-color: #007BFF;
                color: white;
            }
            
            QPushButton:hover {
                background-color: #0069d9;
            }
            
            QPushButton:disabled {
                background-color: #d1d5db;
            }
            
            QScrollArea {
                border: 1px solid #e5e7eb;
                border-radius: 4px;
                background-color: white;
            }
            
            QComboBox::drop-down {
                subcontrol-origin: padding;
                subcontrol-position: top right;
                width: 20px;
                border-left-width: 1px;
                border-left-color: #d1d5db;
                border-left-style: solid;
                border-top-right-radius: 4px;
                border-bottom-right-radius: 4px;
            }
            
            QComboBox::down-arrow {
                image: url(down_arrow.png);
            }
        """)
    
    def add_schedule(self):
        name = self.name_edit.text().strip() or f"定时任务 {len(self.schedules) + 1}"
        date = self.date_edit.date().toString("yyyy-MM-dd")
        time = self.time_edit.time().toString("hh:mm")
        limit = self.limit_spin.value()
        repeat = ["daily", "weekdays", "weekends", "once"][self.repeat_combo.currentIndex()]
        
        # 检查时间冲突
        if self.has_time_conflict(date, time):
            self.show_message("时间冲突", "该时间点已有定时任务，请选择其他时间")
            return
        
        # 创建新任务
        schedule_id = len(self.schedules) + 1
        schedule = {
            "id": schedule_id,
            "name": name,
            "date": date,
            "time": time,
            "limit": limit,
            "repeat": repeat,
            "enabled": True
        }
        
        self.schedules.append(schedule)
        self.update_schedule_list()
        
        # 重置表单
        self.name_edit.clear()
        self.name_edit.setPlaceholderText(f"定时任务 {len(self.schedules) + 1}")
    
    def has_time_conflict(self, date, time, exclude_id=None):
        for schedule in self.schedules:
            if exclude_id and schedule["id"] == exclude_id:
                continue
            if schedule["date"] == date and schedule["time"] == time:
                return True
        return False
    
    def update_schedule_list(self):
        # 清空现有布局
        while self.schedule_layout.count():
            child = self.schedule_layout.takeAt(0)
            if child.widget():
                child.widget().deleteLater()
        
        # 如果没有任务，显示提示
        if not self.schedules:
            no_schedule_label = QLabel("暂无定时任务\n点击上方'添加任务'按钮创建")
            no_schedule_label.setAlignment(Qt.AlignCenter)
            no_schedule_label.setStyleSheet("color: #9ca3af; font-size: 14px;")
            self.schedule_layout.addWidget(no_schedule_label)
            return
        
        # 添加所有任务项
        for schedule in self.schedules:
            item = ScheduleItem(
                schedule["id"],
                schedule["name"],
                schedule["date"],
                schedule["time"],
                schedule["limit"],
                schedule["repeat"],
                schedule["enabled"]
            )
            item.deleteClicked.connect(self.delete_schedule)
            item.toggleClicked.connect(self.toggle_schedule)
            self.schedule_layout.addWidget(item)
        
        # 添加弹簧使内容顶部对齐
        self.schedule_layout.addStretch()
    
    def delete_schedule(self, schedule_id):
        self.schedules = [s for s in self.schedules if s["id"] != schedule_id]
        self.update_schedule_list()
    
    def toggle_schedule(self, schedule_id):
        for schedule in self.schedules:
            if schedule["id"] == schedule_id:
                schedule["enabled"] = not schedule["enabled"]
                break
        self.update_schedule_list()
    
    def show_message(self, title, message):
        msg_box = QMessageBox(self)
        msg_box.setWindowTitle(title)
        msg_box.setText(message)
        msg_box.exec_()

class MainWindow(QMainWindow):
    def __init__(self):
        super().__init__()
        self.setWindowTitle("微加加 - 微信好友批量添加工具")
        self.setMinimumSize(800, 600)
        
        self.init_ui()
    
    def init_ui(self):
        # 主控件
        central_widget = QWidget()
        self.setCentralWidget(central_widget)
        
        # 主布局
        main_layout = QHBoxLayout()
        central_widget.setLayout(main_layout)
        
        # 左侧菜单
        menu_widget = QWidget()
        menu_widget.setFixedWidth(200)
        menu_layout = QVBoxLayout()
        menu_widget.setLayout(menu_layout)
        
        # 菜单项
        menu_title = QLabel("功能菜单")
        menu_title.setStyleSheet("font-weight: bold; padding: 10px; color: #6b7280;")
        menu_layout.addWidget(menu_title)
        
        self.add_friend_btn = QPushButton("批量添加好友")
        self.add_friend_btn.setCheckable(True)
        self.add_friend_btn.setChecked(True)
        
        self.group_add_btn = QPushButton("微信群加好友")
        self.group_add_btn.setEnabled(False)
        
        self.settings_btn = QPushButton("系统设置")
        self.help_btn = QPushButton("帮助中心")
        
        menu_layout.addWidget(self.add_friend_btn)
        menu_layout.addWidget(self.group_add_btn)
        menu_layout.addWidget(self.settings_btn)
        menu_layout.addWidget(self.help_btn)
        menu_layout.addStretch()
        
        # 右侧内容
        content_widget = QWidget()
        content_layout = QVBoxLayout()
        content_widget.setLayout(content_layout)
        
        # 标题
        title_label = QLabel("批量添加好友")
        title_label.setStyleSheet("font-size: 18px; font-weight: bold; color: #1f2937;")
        content_layout.addWidget(title_label)
        
        # 表单区域
        form_widget = QWidget()
        form_layout = QVBoxLayout()
        form_widget.setLayout(form_layout)
        
        # 申请信息
        apply_msg_label = QLabel("申请好友信息 (使用 {name} 占位):")
        self.apply_msg_edit = QTextEdit()
        self.apply_msg_edit.setPlainText("您好，我是{name}，想加您为微信好友")
        self.apply_msg_edit.setMaximumHeight(80)
        
        # 备注前缀
        prefix_label = QLabel("备注前缀:")
        self.prefix_edit = QLineEdit("21届土木工程")
        
        # 文件选择
        file_label = QLabel("选择Excel文件:")
        file_layout = QHBoxLayout()
        self.file_btn = QPushButton("选择文件")
        self.file_btn.setIcon(QIcon.fromTheme("document-open"))
        self.file_label = QLabel("未选择文件")
        self.file_label.setStyleSheet("color: #6b7280;")
        file_layout.addWidget(self.file_btn)
        file_layout.addWidget(self.file_label)
        file_layout.addStretch()
        
        # 定时任务
        schedule_layout = QHBoxLayout()
        self.schedule_check = QCheckBox("设置定时任务")
        self.manage_schedule_btn = QPushButton("管理任务")
        self.manage_schedule_btn.setIcon(QIcon.fromTheme("clock"))
        self.manage_schedule_btn.clicked.connect(self.show_schedule_dialog)
        schedule_layout.addWidget(self.schedule_check)
        schedule_layout.addWidget(self.manage_schedule_btn)
        schedule_layout.addStretch()
        
        # 记住设置
        remember_check = QCheckBox("记住设置内容")
        remember_check.setChecked(True)
        
        # 开始按钮
        start_btn = QPushButton("开始添加好友")
        start_btn.setIcon(QIcon.fromTheme("media-playback-start"))
        
        # 组装表单
        form_layout.addWidget(apply_msg_label)
        form_layout.addWidget(self.apply_msg_edit)
        form_layout.addSpacing(10)
        form_layout.addWidget(prefix_label)
        form_layout.addWidget(self.prefix_edit)
        form_layout.addSpacing(10)
        form_layout.addWidget(file_label)
        form_layout.addLayout(file_layout)
        form_layout.addSpacing(10)
        form_layout.addLayout(schedule_layout)
        form_layout.addSpacing(10)
        form_layout.addWidget(remember_check)
        form_layout.addSpacing(20)
        form_layout.addWidget(start_btn)
        
        # 进度区域
        progress_widget = QWidget()
        progress_layout = QVBoxLayout()
        progress_widget.setLayout(progress_layout)
        
        progress_title = QLabel("任务进度")
        progress_title.setStyleSheet("font-weight: bold; color: #1f2937;")
        
        self.progress_bar = QProgressBar()
        self.progress_bar.setRange(0, 100)
        self.progress_bar.setValue(0)
        
        progress_status_layout = QHBoxLayout()
        self.progress_count_label = QLabel("0/0 完成")
        self.progress_status_label = QLabel("准备就绪")
        self.progress_status_label.setStyleSheet("color: #6b7280;")
        progress_status_layout.addWidget(self.progress_count_label)
        progress_status_layout.addStretch()
        progress_status_layout.addWidget(self.progress_status_label)
        
        self.task_log = QTextEdit()
        self.task_log.setReadOnly(True)
        self.task_log.setMaximumHeight(150)
        
        progress_layout.addWidget(progress_title)
        progress_layout.addWidget(self.progress_bar)
        progress_layout.addLayout(progress_status_layout)
        progress_layout.addWidget(self.task_log)
        
        # 组装内容区域
        content_layout.addWidget(form_widget)
        content_layout.addWidget(progress_widget)
        
        # 添加到主布局
        main_layout.addWidget(menu_widget)
        main_layout.addWidget(content_widget)
        
        # 设置样式
        self.setup_styles()
    
    def setup_styles(self):
        self.setStyleSheet("""
            QMainWindow {
                background-color: #f3f4f6;
            }
            
            QWidget {
                background-color: transparent;
            }
            
            /* 左侧菜单样式 */
            QPushButton {
                padding: 8px 12px;
                text-align: left;
                border-radius: 4px;
                background-color: transparent;
                color: #4b5563;
            }
            
            QPushButton:hover {
                background-color: #e5e7eb;
            }
            
            QPushButton:checked {
                background-color: #d1fae5;
                color: #065f46;
                font-weight: bold;
            }
            
            QPushButton:disabled {
                color: #9ca3af;
            }
            
            /* 右侧内容区域 */
            QTextEdit, QLineEdit {
                border: 1px solid #d1d5db;
                border-radius: 4px;
                padding: 5px;
                background-color: white;
            }
            
            QProgressBar {
                border: 1px solid #d1d5db;
                border-radius: 4px;
                height: 10px;
                text-align: center;
            }
            
            QProgressBar::chunk {
                background-color: #10b981;
                border-radius: 3px;
            }
            
            QCheckBox {
                spacing: 5px;
            }
        """)
    
    def show_schedule_dialog(self):
        dialog = ScheduleDialog(self)
        dialog.exec_()

if __name__ == "__main__":
    app = QApplication(sys.argv)
    
    # 设置应用程序样式
    app.setStyle("Fusion")
    
    window = MainWindow()
    window.show()
    
    sys.exit(app.exec_())